<template>
  <view>
    <navbar />
    <u--form ref="form" :model="temp">
      <u-form-item label="上级目录:" :border-bottom="true">
        <tree-select v-model="temp.parentId" :list="list"/>
      </u-form-item>
      <u-form-item label="名称:" :border-bottom="true">
        <u--input v-model="temp.name" placeholder="请输入名称" border="none" />
      </u-form-item>
      <u-form-item label="编码:" :border-bottom="true">
        <u--input v-model="temp.code" placeholder="请输入编码" border="none" />
      </u-form-item>
      <u-form-item label="经理:" :border-bottom="true">
        <system-user v-model="temp.manager" placeholder="请选择经理" />
      </u-form-item>
      <u-form-item label="地址:" :border-bottom="true">
        <u--input v-model="temp.address" placeholder="请输入地址" border="none" />
      </u-form-item>
    </u--form>
    <u-button :loading="loading" class="submit-button" type="primary" shape="circle" @click="submit">提交</u-button>
  </view>
</template>

<script>
import { fetchDepartmentList, getDepartment, createDepartment, updateDepartment } from '@/api/department/department.js'
import TreeSelect from '@/components/TreeSelect/treeSelect.vue'
import SystemUser from '@/components/System/systemUser'
export default {
  name: 'DepartmentForm',
  components: {
    TreeSelect,
    SystemUser
  },
  data() {
    return {
      loading: false,
      list: [],
      temp: {},
      rules: {}
    }
  },
  onLoad(query) {
    this.getList()
    this.temp.id = query.id
    if (this.temp.id) {
      this.getDetail(query.id)
    }
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  methods: {
    // 获取列表
    getList() {
      fetchDepartmentList().then(response => {
        if (response.data.success) {
          this.list = response.data.data
        }
      })
    },
    // 详情
    getDetail(id) {
      getDepartment(id).then(response => {
        if (response.data.success) {
          this.temp = response.data.data
        }
      })
    },
    // 提交表单
    submit() {
      if (this.isNull(this.rules)) {
        !this.temp.id ? this.create() : this.update()
        return
      }
      this.$refs.form.validate().then(() => {
        !this.temp.id ? this.create() : this.update()
      })
    },
    // 新建
    create() {
      this.loading = true
      createDepartment(this.temp).then(response => {
        this.loading = false
        if (response.data.success) {
          this.$uni.showToast(response.data.msg)
          this.$uni.goBack()
        }
      })
    },
    // 更新
    update() {
      this.loading = true
      updateDepartment(this.temp).then(response => {
        this.loading = false
        if (response.data.success) {
          this.$uni.showToast(response.data.msg)
          this.$uni.goBack()
        }
      })
    }
  }
}
</script>
